<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title>自由课程中的作业提交</title>
		<script src="../../script/mui.min.js"></script>
		<script src="../../script/jquery.min.js"></script>
		<script src="../../script/jquery.knob.js"></script>
		  <link rel="stylesheet" type="text/css" href="../../css/mui.min.css">
		<link rel="stylesheet" href="../../css/mui.min.css" />
		<link rel="stylesheet" href="../../css/timecontrol.min.css" />
		<link rel="stylesheet" href="../../css/CFNetPP_Base.css">
		<link rel="stylesheet" href="../../css/base.css"/>
		<link rel="stylesheet" type="text/css" href="../../css/weui.min.css">
		<link rel="stylesheet" type="text/css" href="../../css/attachmentCss.css">
		<style>
			body {
			}
			.title_ms {
				margin-left: 16px;
				font-size: 15px
			}
			.work_time_text {
				color: #222222;
				padding-left: 18px;
				padding-right: 18px;
				line-height: 30px;
				font-size: 14px;

			}
			.div-border-bottom{
		
			background-color:#222222;
		    width: 100%;
         height: 1px;
			}
			.title {
				line-height: 1.2em;
				font-size: 16px;
				color: #323232;
				padding-left: 10px;
			}
			#bewriteDIV {
				background-color: #FFFFFF;
			}
			.textarea {
				height: 120px;
				font-size: 14px;
				font-family: "微软雅黑";
				color: #909090;
				/*border-top: 1px solid #d9d9d9;*/
				line-height: 25px;
				/* padding: 6px 10px;*/
			}
			.imgDivclass {
				border-top: 1px solid #d9d9d9;
				color: #909090;
				font-size: 14px;
				padding: 10px 10px 0px 10px;
			}
			.CellFrame {
				float: left;
				position: relative;
				padding-left: 10px;
				padding-top: 10px;
				padding-bottom: 10px;
				width: 33%;
				height: 120px
			}
			.picCell {
				width: 100%;
				height: 100%
			}
			.pic_del {
				position: absolute;
				right: -5px;
				width: 20px;
				top: 0px;
			}
		</style>
	</head>
	<body>


		<div id="bewriteDIV" >
			<div class="padding10">
				<p class=" base_black_grey base_title_font">
					描述
				</p>
				<div class="base_dark_grey base_content_font according-2-rows text_indent_2" id="bewrite" onclick="openBewrite()">
				<!--	描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字描述文字-->
				</div>
			</div>
			<div class="div_divider"></div>
			<div style="background-color: #f0f0f0;height:5px"></div>
			<div class="div_divider"></div>
		</div>
		<div class="writeReport" id="zbjs" >
			<div class="bgwhite">
				<div class="work_time_text" id="work_time"></div>
				<div class="div-border-bottom"></div>
				<div class="textare_div ">
					<textarea class="textarea bottom_10" id="homeworkms"  style="color: #363636" placeholder='请在此填写作业内容'></textarea>
				</div>
				<div class="imgDivclass">
					<p style="margin-left: 10px;">
						*最多支持上传9张图片
					</p>
					<div id="addPhoto"></div>
				<!--<div class="CellFrame">
						<img class="pic_del" src="../../icon/icon_shanchuhuise.png">
						<img class="picCell" src="../../icon/icon_picAdd.png" alt="" onclick="selectPhoto()">
					</div>
					<div  class="CellFrame">
						<img class="pic_del" src="../../icon/icon_shanchuhuise.png">
						<img class="picCell" src="../../icon/icon_picAdd.png" alt="" onclick="selectPhoto()">
					</div>
					<div   class="CellFrame">
						<img class="pic_del" src="../../icon/icon_shanchuhuise.png">
						<img class="picCell" src="../../icon/icon_picAdd.png" alt="" onclick="selectPhoto()">
					</div>-->
					
					
				</div>
			</div>
			<div class="myScore top_10 "style=" width: 100%">
				<p class="title " >
					添加附件
				</p>
				<div class="fileDiv " id="imgDiv" >
					<ul id="filehtml" >
						<!--'
						<li dataid="' + num + '"  class="mui-table-view-cell " >
						<a class=" base_content_font" href="#" ><span class="base_grey left_text"> NameArr[i] + '</span> <span id="company_name " class="base_grey right_text padding_left_10"> SizeArr[i] + '</span> <img class="  right"    src="../../image/remove.png"  width="20" height="20"  onClick="deletefile(' + i + ')" ></a>
						</li>
						<div id="fuj">
						<a  href="javascript:;" class="weui_btn weui_btn_mini weui_btn_default top_10" onclick="AddFile()">添加附件</a>
						<span style="margin-left: 5px"class="font11">仅支持以下格式:('jpg', 'gif', 'png', 'jpeg', 'bmp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf', 'txt')</span>
						</div>-->
					</ul>
				</div>
			</div>
			<button id="sumbit_bt" type="button" class=" top_30 bottom_30 mui-btn mui-btn-warning mui-btn-block  " onclick="Upload_data()">
				提交
			</button>
		</div>
		<div id="picture" class="mui-popover mui-popover-action mui-popover-bottom">
			<ul class="mui-table-view">
				<li class="mui-table-view-cell">
					<a href="#" typeid="0" style="color:#222222;">拍照</a>
				
				</li>
				<li class="mui-table-view-cell">
					<a href="#" typeid="1" style="color:#222222;">从相册选取</a>
				</li>
			</ul>
			<ul class="mui-table-view">
				<li class="mui-table-view-cell">
					<a href="#picture" typeid="2" style="color:#222222;"><b>取消</b></a>
				</li>
			</ul>
		</div>
		<div id="offlineAlert" class="weui_dialog_confirm" style="display: none;">
			<div class="weui_mask"></div>
			<div class="weui_dialog">
				<div class="weui_dialog_hd">
					<strong class="weui_dialog_title">是否放弃在此页面操作？</strong>
				</div>
				<div class="weui_dialog_bd"></div>
				<div class="weui_dialog_ft">
					<a onclick="cleanCancel()" href="#" class="weui_btn_dialog default"  style="color:#18b4ed">取消</a>
					<a onclick="cleanConfirm()" href="#" class="weui_btn_dialog primary"  style="color:#18b4ed">确定</a>
				</div>
			</div>
		</div>
		<div class="noSign" hidden="hidden" id="noData">
			<div style="width: 100%;height: 30px;"></div>
			<img src="../../image/icon_img.png" width="60%">
			<p class="font16 top_15 base_dark_grey" >
				暂无数据
			</p>
		</div>
	</body>
	<script type="text/javascript" src="../../script/jquery.min.js"></script>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/MD5.js"></script>
	
	<script src="../../script/common.js"></script>
	<script src="../../script/timeStampTool.js"></script>
	<script src="../../script/processing_images.js"></script>
	<script type="text/javascript" src="../../script/requestTool.js"></script>
	<script type="text/javascript" src="../../script/mui.min.js"></script>
	<script type="text/javascript">
		//附件地址集合
		var urlArr = new Array();
		//文件大小
		var SizeArr = [];
		//上传后的图片路径对象
		var picurls = [];
		//文件名
		var NameArr = [];
		//图片数组
		var ImgArr = [];
		//图片上传后数组
		var ImgUploadArr = [];
		//空格回车正则判断
		var parten = /^\s*$/;
		//上传文件路径
		var url = "";
		var str = "";
		//判断是否选中上传附件
		var ischeak = 0;
		// 上传的文本内容
		var ts = "";
		var arr = new Array('jpg', 'gif', 'png', 'jpeg', 'bmp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf', 'txt','mp4','MP4','zip','rar');
		var homeworkms = '';
		var strfile = "";
		//上传得文件
		var pids = "";
		var chapterids = "";
		var uids = "";
		var jids = "";
		var data = new Object();
		var work_name = "";
		var work_desc = "";
		var work_time = "";
		var sid = 0;
		var filed = [];
		var filesizes = "";
		// 文件大小
		var isnulls = "";
		apiready = function() {
			isnulls = $api.getStorage("zyisnull");
			if (isnulls == "0") {
				$("#noData").show();
				api.addEventListener({
					name : 'new_frameback1'
				}, function(ret, err) {
					//coding...
					backClick();
				});
			} else {
				$("#zbjs").show();
				data = api.pageParam.datas;
				work_desc = data.json.workbewrite;
				work_time = "作业提交时间：" + timeStringWithTimeStamp(data.json.stime.toString()) + " 至 " + timeStringWithTimeStamp(data.json.etime.toString());
				api.addEventListener({
					name : 'new_frameback1'
				}, function(ret, err) {
					//coding...
					showAlert();
				});
				listfile();
				listImg();
				$('#fuj').show();
				setupBewriteShowOrHide();
				uids = $api.getStorage('cfnetppuid');
				pids = api.pageParam.pid;
				chapterids = api.pageParam.chapterid;
				jids = $api.getStorage('cfnetppjxid');
			}
			api.addEventListener({
				name : 'HomeWorkBackNotifi'
			}, function(ret, err) {
				if ($('#homeworkms').val().length > 0) {
					$('#offlineAlert').show();
				} else {
					api.sendEvent({
						name : 'HomeWorkConfirmBackNotifi'
					});
				}
			});
		}
		function setupBewriteShowOrHide() {
			var bewrite = data.json.workbewrite;
			if (bewrite != "" && bewrite != null && bewrite != undefined) {
				$('#bewriteDIV').show();
				if (removeHTMLTag(bewrite).length > 0) {
					$('#bewrite').html(removeHTMLTag(bewrite));
				} else {
					$('#bewrite').html('点击查看详情');
				}
				hight1 = $('#bewriteDIV').height();
			}
		}
			function setupImage() {
						var newWidth = api.winWidth - 20;
						$("img").each(function(i) {
							var oldWith = $(this).width();
							if (oldWith == 0) {
								setTimeout(function() {
									setupImage();
								}, 500);
								return;
							}
							if (oldWith > newWidth) {
								var oldHeight = $(this).height();
								var newHeight = oldHeight * (newWidth / oldWith);
								$(this).width(newWidth);
								$(this).height(newHeight);
							}
						});
					}
		function openBewrite() {
			api.openWin({useWKWebView:true,
				name : 'Student_Free_bewrite',
				url : 'Student_Free_bewrite.html',
				pageParam : {
					cdetailtitle : data.json.workname,
					bewrite : data.json.workbewrite,
					is_dis_bewrite : data.json.is_dis_bewrite
				}
			});
		}

		function loadData() {
			homeworkms = $('#homeworkms').val();
		}

		//UI显示
		function listfile() {
			var str2 = "仅支持以下格式:jpg, gif, png, jpeg, bmp, doc, xls, ppt, docx, xlsx, pptx, pdf, txt,mp4,MP4,zip,rar";
			$("#work_time").text(work_time);
			// setupImage();
			var num = urlArr.length;
			var imageHtmls = '';
			if (num > 0 && num < 11) {
				for ( i = 0; i < num; i++) {
					var imageHtml = '<li dataid="' + num + '"  class="mui-table-view-cell " >' + '<a class=" base_content_font" href="#" >' + '<span class="base_grey left_text">' + NameArr[i] + '</span>' + ' <span id="company_name " class="base_grey right_text padding_left_10">' + SizeArr[i] + '</span> <img class="  right"    src="../../image/remove.png"  width="20" height="20"  onClick="deletefile(' + i + ')" >' + '</a>' + '</li>';
					imageHtmls = imageHtmls + imageHtml;
				}
			}
			//			var seleimg = '<a id="fuj" href="javascript:;" class="weui_btn weui_btn_mini weui_btn_default top_10" onclick="AddFile()">' + '添加附件' + '</a>';
			var seleimg = '<div id="fuj">' + '<a  href="javascript:;" class="weui_btn weui_btn_mini weui_btn_default top_10" onclick="AddFile()">添加附件</a>' + '<span style="margin-left: 5px"class="font11 base_grey">' + str2 + ',大小不能超过50M</span>' + '</div>';
			imageHtmls = imageHtmls + seleimg;
			$("#filehtml").html(imageHtmls);
		}
		//添加附件
		function miuilist() {
			var fileBrowser = api.require('fileBrowser');
			fileBrowser.open(function(ret, err) {
				if (ret) {
					//文件地址
					var url = ret.url;
					fileBrowser.close();
					//文件名
					var fileName = splitFileName(url);
					//文件后缀ming
					var ext = fileName.replace(/.+\./, "");
					//小写格式
					var extLower = ext.toLowerCase();
					////根据文件地址判断文件大小是否超过10M
					var fs = api.require('fs');
					fs.getAttribute({
						path : url
					}, function(ret, err) {
						//大小，10M转换为b
						var fileSize = ret.attribute.size;
						if (fileSize > 1024*1024*50) {//50M
							ShowToast('上传的文件过大');
						} else if (arr.toString().indexOf(extLower) == -1) {
							ShowToast('文件格式不符合要求');
						} else if (urlArr.toString().indexOf(url) > -1) {
							ShowToast('不允许重复提交');
						} else {
							urlArr.push(url);
							var num = urlArr.length;
							SizeArr.push(bytesToSize(ret.attribute.size));
							NameArr.push(fileName);
							listfile();
							if (num > 0) {
								api.showProgress({
									style : 'default',
									animationType : 'fade',
									title : '上传文件中...',
									text : '请稍后...',
									modal : false
								});
								CFNetUploadFile(url);
						
							} else {
								str = '';
							}
							$('#fuj').hide();
						}
					});
				}
			});
		}

		//删除附件
		function deletefile(i) {
			//删除第i个位置开始第一个元素
			urlArr.splice(i, 1);
			picurls.splice(i, 1);
			SizeArr.splice(i, 1);
			NameArr.splice(i, 1);
			listfile();
			$('#fuj').show();
		}

		//添加附件
		function AddFile() {
			if (api.systemType == "ios") {
				ShowToast('苹果手机不支持上传附件，请登录网页进行提交！');
			} else {
				miuilist();
			}
		}

		function Upload_data() {
//			console.log(JSON.stringify(ImgUploadArr));
//			return;
			var msgs = '';
			ts = $('#homeworkms').val();
			if (ts == "" &&picurls.length > 0&& ImgUploadArr.length > 0) {
				api.toast({
					msg : '您未填写作业内容，不可提交'
				});
				return ;
			} 
			showProgress();
			uoloads();
		}

		//UI显示图片
		function listImg(){
		
			var num = ImgArr.length;
			var imageHtmls = '';
			if (num > 0 && num < 11) {
				for ( i = 0; i < num; i++) {
		            var photoPath = ImgArr[i];
					var imageHtml = '<div class="CellFrame" id='+i+'>'+
						'<img class="pic_del" src="../../icon/icon_shanchuhuise.png" onclick="delPhoto('+i+')">'+
						'<img class="picCell" src="'+photoPath+'" alt="" >'+
					'</div>';
					imageHtmls = imageHtmls + imageHtml;
				}
			}
			var seleimg = '';
		    if(num<9){
			   seleimg = '<div   class="CellFrame"><img class="picCell" src="../../icon/icon_picAdd.png" alt="" onclick="selectPhoto()"></div>';
			}
			imageHtmls = imageHtmls + seleimg;
			$("#addPhoto").html(imageHtmls);
		}
		//弹出拍照的底部框
		function selectPhoto(){
			mui('#picture').popover('toggle');
			mui('body').on('tap', '.mui-popover-action li>a', function() {
				var typeid = $(this).attr('typeid');
				mui('#picture').popover('hide');
				if (typeid == 0) {//拍照
					api.getPicture({
						sourceType : 'camera',
						encodingType : 'png',
						mediaValue : 'pic',
						destinationType : 'url',
						allowEdit : true,
						quality : 50,
						saveToPhotoAlbum : false
					}, function(ret, err) {
						if ($('#picture').is(':visible')) {
							$('#picture').hide();
						}
						if (ret) {
							var photoPath = ret.data;
							if (photoPath != '') {
								showProgress();
								ImgArr.push(photoPath);
								listImg();
								//	上传文件至阿里云
							  	UploadFile_ali(Upload_File_img, photoPath, function(ret) {
									if (ret) {
										hideProgress();
										//	var ImgData = '';
										//	ImgData["name"] = 1;//作业
										//	homeWorkDataImgData["size"] = fileSize;
										//	ImgData["url"] = coursename;
										ImgUploadArr.push(ret.fileurl);
									}
								});
							}
						} 
					});
				} else if (typeid == 1) {//从相册选择
					selectPhotos(function(ret){
						addAlbumPicWithArr(ret.list, function(){
							listImg();
						});
					});
					return;
					api.getPicture({
						sourceType : 'album',
						encodingType : 'png',
						mediaValue : 'pic',
						destinationType : 'url',
						allowEdit : true,
						quality : 50,
						saveToPhotoAlbum : false
					}, function(ret, err) {
						if ($('#picture').is(':visible')) {
							$('#picture').hide();
						}
						if (ret) {
							var photoPath = ret.data;
							if (photoPath != '') {
							   	showProgress();
								ImgArr.push(photoPath);
								listImg();
								//上传文件至阿里云
							  	UploadFile_ali(Upload_File_img, photoPath, function(ret) {
									if (ret) {
										hideProgress();
										ImgUploadArr.push(ret.fileurl);
									}
								});
							}
						} 
					});
				}
			});
		}
		function addAlbumPicWithArr(picArr, callback){
			if (picArr == null || picArr == undefined || picArr == '') {
				return;
			}
			api.showProgress({
			    style: 'default',
			    animationType: 'fade',
			    title: '',
			    text: '上传图片中...',
			    modal: false
			});
			var index = 0;
			for (var i = 0; i < picArr.length; i++) {
				var picData = picArr[i];
				ImgArr.push(picData.path);
				addAlbumPic(picData, function(ret){
					if (ret) {
						ImgUploadArr.push(ret);
					}
					index++;
					if (index == picArr.length) {
						api.hideProgress();
						callback();
					}
				});
			}	
		}
		function addAlbumPic(picData, callback){
			UploadFile_ali(Upload_File_img, picData.path, function(ret) {
				if (ret) {
					callback(ret.fileurl);
				}else{
					callback(null);
				}
			});
		}
		//打开相册
		function selectPhotos(callback){
			var maxNum = 9 - ImgUploadArr.length;
			if (maxNum <= 0) {
				return;
			}
			var UIMediaScanner = api.require('UIMediaScanner');
			UIMediaScanner.open({
			    type: 'picture',
			    column: 4,
			    classify: true,
			    max: maxNum,
			    sort: {
			        key: 'time',
			        order: 'desc'
			    },
			    texts: {
			        stateText: '已选择*项',
			        cancelText: '取消',
			        finishText: '完成'
			    },
			    styles: {
			        bg: '#fff',
			        mark: {
			            icon: '',
			            position: 'bottom_left',
			            size: 20
			        },
			        nav: {
			            bg: '#eee',
			            stateColor: '#000',
			            stateSize: 18,
			            cancelBg: 'rgba(0,0,0,0)',
			            cancelColor: '#000',
			            cancelSize: 18,
			            finishBg: 'rgba(0,0,0,0)',
			            finishColor: '#000',
			            finishSize: 18
			        }
			    },
			    scrollToBottom: {
			        intervalTime: 3,
			        anim: true
			    },
			    exchange: true,
			    rotation: true
			}, function(ret) {
				callback(ret);
			});
		}
	    //删除图片
	    function delPhoto(i){
	    	ImgArr.splice(i, 1);
			ImgUploadArr.splice(i, 1);
			listImg();
	    }
		function showAlert() {
			loadData();
			if (homeworkms.length > 0) {
				$('#offlineAlert').show();
			} else {
				backClick();
			}
		}

		function cleanCancel() {
			$('#offlineAlert').hide();
		}

		//确定
		function cleanConfirm() {
			$('#offlineAlert').hide();
			backClick();
		}

		// 新接口作业上传测试
		function uoloads() {
	
			var url = '';
			var size = '';
			var name = '';
			if (picurls.length > 0) {
				url = picurls[0];
				name = NameArr[0];
				size = SizeArr[0];
			}

			var params = {
				uid : uids,
				jid : jids,
				pid : pids,
				cid :api.pageParam.cid,
				vid : chapterids,
				content : ts,
				fileurl : url,
				filename : name,
				filesize : size,
				imglist : ImgUploadArr
			};
			console.log("提交参数:"+JSON.stringify(params));
			cfnetppPOST(url_subWork, params, true, function(data, status) {
				hideProgress();
				SendBusinessOperationsLogNotifi('自由课程提交作业页', '071', params, params, '', data, '自由课程提交作业', '071-01')
				if (data.code == "200") {
					api.sendEvent({
						name : 'freeCourseRecordNotifi',
						extra : {
							uid : uids,
							jid : jids,
							cid : api.pageParam.cid,
							vid : chapterids, //章节id
							pid : pids
						}
					});
					api.toast({
						msg : '作业上传成功'
					});
					api.sendEvent({
						name : 'workinfo'
					});
					api.closeFrame({
						name : "new_student_study_freecourse_homework"
					});
				} else {
					var tishi = "数据请求出错！！！";
					if (data.code == "100" || data.code == "109") {
						tishi = "作业提交失败";
					}else if (data.code == "101") {
						tishi = "参数错误";
					}else if (data.code == "106") {
						tishi = "章节未找见";
					}else if (data.code == "107") {
						tishi = "作业未找见";
					}else if (data.code == "118") {
						tishi = "作业已经过期";
					}else if (data.code == "119") {
						tishi = "作业已经提交过";
					}else if(data.code == "120"){
						tishi = "此作业只能由小组长提交！";
					}
					api.toast({
						msg : tishi
					});
				}
			});
		}

    	function CFNetUploadFile(path){
			UploadFile_ali(Upload_File_file,path,function (ret) {
				hideProgress();
				console.log(JSON.stringify(ret));
				if(ret.status){
					picurls.push(ret.fileurl);
					api.toast({
						msg:'上传成功'
					});
				}else{
					api.toast({
						msg:'上传失败，请重新上传'
					});
				}
			});
			// var upfile = api.require('CFNetUploadFile');
			// var param = {
			// 		url : url_uploadSingleFiles,
			// 	uid : uids,//uid
			// 	path : path,//路径
			// };
// 			upfile.uploadFile(param,function(ret,err){
// 			    hideProgress();
// //				alert(JSON.stringify(ret));
// 				if(ret.status== true){
// 					picurls.push(ret.uploadFileUrl);
// 					api.toast({
//                   		msg:'上传成功'
//               		});
// 				}else{
// 					api.toast({
// 	                  	msg:'上传失败，请重新上传'
//                   	});
// 				}
// 			});
		}
	</script>
</html>